//
//  XDTradeRecordsViewController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/2/13.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//

#import "XDTradeRecordsViewController.h"
#import "AFHTTPSessionManager+POST.h"
#import "MJExtension.h"
#import "XDTradeRecordsModel.h"
#import "XDTradeRecordsCell.h"
#import "UIButton+Extension.h"
#import "XDWithdrawProgressViewController.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
@interface XDTradeRecordsViewController ()<UITableViewDelegate, UITableViewDataSource,XDTradeRecordsCellDelete>

@property (nonatomic, strong) NSArray *tradeRecordsArr;

@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *resultArr;


@property (nonatomic, strong) NSMutableArray *mutArr;


@property (nonatomic, weak) UIView *selectView;

@property (nonatomic, weak) UIView *titleCoverView;

@property (nonatomic, weak) UIButton *rightBtn;
@end

@implementation XDTradeRecordsViewController
- (NSArray *)tradeRecordsArr {
    if (_tradeRecordsArr == nil) {
        _tradeRecordsArr = [NSArray array];
    }
    return _tradeRecordsArr;
}
- (NSMutableArray *)resultArr {
    if (_resultArr == nil) {
        _resultArr = [NSMutableArray array];
    }
    return _resultArr;
}
- (UIView *)titleCoverView {
    if (_titleCoverView == nil) {
        UIView *titleCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        titleCoverView.backgroundColor = kColorRGBA(0, 0, 0, 0.5);
        _titleCoverView = titleCoverView;
        [self.view addSubview:titleCoverView];
        
    }
    
    return _titleCoverView;
}
- (UIView *)selectView {
    
    if (_selectView == nil) {
        
        UIView *selectView = [[UIView alloc] initWithFrame:CGRectMake(0, - 200, kScreenW, 140)];
        selectView.backgroundColor = kColorRGB(255, 255, 255);
        [self.view addSubview:selectView];
        self.selectView = selectView;
        UIButton *allBtn = [UIButton buttonWithFrame:CGRectMake(28, 32, (kScreenW - 56 - 22) / 3, 33) norBagImgNamed:@"greyBtn" selBagImgNamed:@"yellowBtn" title:@"充值" titleColor:kColorRGB(0, 0, 0) selColor:kColorRGB(187,147,115) titleFont:14  target:self selector:@selector(allSelectBtnClicK:)];
        allBtn.adjustsImageWhenHighlighted = NO;
        allBtn.tag = 300;
        [allBtn setBackgroundImage:[UIImage imageNamed:@"yellowBtn"] forState:UIControlStateDisabled];
        [selectView addSubview:allBtn];
        
        UIButton *planPostBtn = [UIButton buttonWithFrame:CGRectMake(CGRectGetMaxX(allBtn.frame) + 11, 32, (kScreenW - 56 - 22) / 3, 33) norBagImgNamed:@"greyBtn" selBagImgNamed:@"yellowBtn" title:@"提现" titleColor:kColorRGB(0, 0, 0) selColor:kColorRGB(187,147,115) titleFont:14  target:self selector:@selector(allSelectBtnClicK:)];
        planPostBtn.adjustsImageWhenHighlighted = NO;
        planPostBtn.tag = 301;
        [selectView addSubview:planPostBtn];
        
        UIButton *sanPostBtn = [UIButton buttonWithFrame:CGRectMake(CGRectGetMaxX(planPostBtn.frame) + 11, 32, (kScreenW - 56 - 22) / 3, 33) norBagImgNamed:@"greyBtn" selBagImgNamed:@"yellowBtn" title:@"手续费" titleColor:kColorRGB(0, 0, 0) selColor:kColorRGB(187,147,115) titleFont:14  target:self selector:@selector(allSelectBtnClicK:)];
        sanPostBtn.adjustsImageWhenHighlighted = NO;
        sanPostBtn.tag = 302;
        [selectView addSubview:sanPostBtn];
        
        UIButton *newBtn = [UIButton buttonWithFrame:CGRectMake(28, CGRectGetMaxY(allBtn.frame) + 11, (kScreenW - 56 - 22) / 3, 33) norBagImgNamed:@"greyBtn" selBagImgNamed:@"yellowBtn" title:@"收益" titleColor:kColorRGB(0, 0, 0) selColor:kColorRGB(187,147,115) titleFont:14  target:self selector:@selector(allSelectBtnClicK:)];
        newBtn.adjustsImageWhenHighlighted = NO;
        newBtn.tag = 303;
        [selectView addSubview:newBtn];
        
        UIButton *Btn = [UIButton buttonWithFrame:CGRectMake(CGRectGetMaxX(newBtn.frame) + 11, CGRectGetMaxY(allBtn.frame) + 11, (kScreenW - 56 - 22) / 3, 33) norBagImgNamed:@"greyBtn" selBagImgNamed:@"yellowBtn" title:@"投资" titleColor:kColorRGB(0, 0, 0) selColor:kColorRGB(187,147,115) titleFont:14  target:self selector:@selector(allSelectBtnClicK:)];
        Btn.adjustsImageWhenHighlighted = NO;
        Btn.tag = 304;
        [selectView addSubview:Btn];
    }
    
    return _selectView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadData];
    [self setupUI];
}

- (void)loadData {
    
    NSDictionary * param = @{@"method":@"getTradeRecords",@"status":@"ALL",@"page":@"0"};
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"100000"]) {
            
            NSArray *arr = responseObject[@"result"][@"tradeRecords"];
            NSMutableArray *mutArr = [NSMutableArray arrayWithArray:arr];
            if (mutArr.count > 1) {
                for (int i =0; i<[mutArr count]-1; i++) {
                    for (int j =0; j<[mutArr count]-1-i; j++) {
                        
                        if(([mutArr[j][@"ctime"] compare:mutArr[j+1][@"ctime"]]) == NSOrderedAscending){
                            
                            //交换
                            
                            [mutArr exchangeObjectAtIndex:j withObjectAtIndex:j+1];
                        }
                        
                    }
                    
                }
            }
           
            [self resultArray:mutArr];
            if (self.mutArr.count > 0) {
                 [self.resultArr addObject:self.mutArr];
            }
            
            self.tradeRecordsArr = [XDTradeRecordsModel mj_objectArrayWithKeyValuesArray:self.resultArr];
            
            if (self.tradeRecordsArr.count) {
                
                [self.tableView reloadData];
            } else {
                
                [ZHRTRequestFailureShowViewOrDetail showNoDataForView:self.view imageNamed:@"noTrade" text:@"暂无交易明细" type:0];
            }
            
            
            
        } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
            
            
        } else {
            
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}

- (void)resultArray:(NSMutableArray *)arr
{
    if (arr.count > 0) {
        __block NSString *firstCtime = arr[0][@"ctime"];
        
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate *date = [fmt dateFromString:firstCtime];
        //
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM";
        firstCtime = [dateFormatter stringFromDate:date];
      
        NSMutableArray *mutArr = [NSMutableArray array];
        self.mutArr = mutArr;
        [arr enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *ctimeStr = [dateFormatter stringFromDate:[fmt dateFromString:dic[@"ctime"]]];
            if ([ctimeStr isEqualToString:firstCtime]) {
                [mutArr addObject:dic];
                
            } else{
                [self.resultArr addObject:mutArr];
                for (NSInteger i = 0; i < idx; i ++) {
                    [arr removeObjectAtIndex:0];
                }
                [self resultArray:arr];
            }
            
        }];
        
        for (NSInteger i = 0; i < arr.count; i ++) {
            [arr removeObjectAtIndex:0];
        }
        }
}

- (void)navigationBarCof {
    self.title = @"交易明细";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:kColorRGB(187,147,115) ,NSFontAttributeName:kBaseFont_(19)}];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self navigationBarCof];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // 禁用 iOS7 返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)setupUI {
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - 64) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
    tableView.tableFooterView = view;
    
    
    UIButton *rightBtn = [UIButton buttonWithFrame:CGRectMake(0, 0, 40, 44) norBagImgNamed:nil selBagImgNamed:nil title:@"筛选" titleColor:kColorRGB(187,147,115) selColor:nil titleFont:14 target:self selector:@selector(rightBarButtonItemClick:)];
    self.rightBtn = rightBtn;
    rightBtn.selected = YES;
    [rightBtn sizeToFit];
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    

    
}

#pragma mark -- table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = self.tradeRecordsArr[section];
    return arr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.tradeRecordsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *myID = @"XDTradeRecordsCell";
    XDTradeRecordsCell *cell = [tableView dequeueReusableCellWithIdentifier:myID];
    if (cell == nil) {
        cell = [[XDTradeRecordsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myID];
    }
    NSArray *arr = self.tradeRecordsArr[indexPath.section];
    XDTradeRecordsModel *model = arr[indexPath.row];
    cell.model = model;
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 60)];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 10, kScreenW, 50)];
    view.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:view];
    UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kScreenW, 50)];
    lb.textAlignment = NSTextAlignmentLeft;
    lb.textColor = kColorRGB(187,147,115);
    lb.font = kBaseFont_(14);
    [view addSubview:lb];
    NSArray *arr = self.tradeRecordsArr[section];
    XDTradeRecordsModel *model = arr[0];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSDate *date = [fmt dateFromString:model.ctime];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy年MM月";
//    NSString *currDate = [dateFormatter stringFromDate:[NSDate date]];
//    if ([model.ctime isEqualToString:currDate]) {
//        lb.text = @"本月";
//    } else {
        lb.text = [dateFormatter stringFromDate:date];
//    }
    UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, kScreenW, 0.5)];
    separatorView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    [headerView addSubview:separatorView];
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, kScreenW - 30, 0.5)];
    separatorView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    return separatorView;
}

- (void)rightBarButtonItemClick:(UIButton *)itemBtn {
    
    if (itemBtn.selected) {
        self.titleCoverView.frame = kScreenB;
        [UIView animateWithDuration:0.5 animations:^{
            self.selectView.frame = CGRectMake(0, 0, kScreenW, 140);
        } completion:^(BOOL finished) {
            
        }];
        itemBtn.selected = NO;
    } else {
        [UIView animateWithDuration:0.5 animations:^{
             self.titleCoverView.backgroundColor = kColorRGBA(0, 0, 0, 0);
            self.selectView.frame = CGRectMake(0, - 200, kScreenW, 140);
        } completion:^(BOOL finished) {
            [self.titleCoverView removeFromSuperview];
            [self.selectView removeFromSuperview];
        }];
        itemBtn.selected = YES;
    }

}

- (void)allSelectBtnClicK: (UIButton *)btn {
    
    btn.selected = YES;
    [UIView animateWithDuration:0.5 animations:^{
        self.titleCoverView.backgroundColor = kColorRGBA(0, 0, 0, 0);
        self.selectView.frame = CGRectMake(0, - 200, kScreenW, 140);
    } completion:^(BOOL finished) {
        [self.titleCoverView removeFromSuperview];
        [self.selectView removeFromSuperview];
    }];
    self.rightBtn.selected = YES;
    
}

- (void)wdStatusBtnPushWithdraw:(UIButton *)btn {
    
    XDWithdrawProgressViewController *withdraw = [[XDWithdrawProgressViewController alloc] init];
    withdraw.wdId = btn.tag;
    [self.navigationController pushViewController:withdraw animated:YES];
    
}
@end
